package rpc.provider;

import lombok.extern.slf4j.Slf4j;
import rpc.enums.RpcError;
import rpc.exception.RpcException;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认的服务注册表
 *
 * @Author wupeijie
 * @Date 2020/11/20 9:54
 */
@Slf4j
public class ServiceProviderImpl implements ServiceProvider {

    //存放接口名+实例
    private static Map<String, Object> serviceMap = new ConcurrentHashMap<>();

    //存放实例名,用来判断实例是否存在
    private static Set<String> registeredService = ConcurrentHashMap.newKeySet();

    @Override
    public <T> void addServiceProvider(T service,String  serviceName) {
        //如果包含，则不再注册
        if (registeredService.contains(serviceName)) return;
        registeredService.add(serviceName);//存放实例，服务对象
        serviceMap.put(serviceName, service); //key-接口名 value-实体名
        log.info("向接口:{} 注册服务:{}", service.getClass().getInterfaces(), serviceName);
    }

    @Override
    public Object getServiceProvider(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if (service == null) {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return service;
    }
}
